package com.origin.onlinesys.web.controllers.modules.finance;

import com.origin.onlinesys.common.controllers.BaseController;
import com.origin.onlinesys.domain.modules.finance.Finance;
import com.origin.onlinesys.domain.modules.finance.FinanceCount;
import com.origin.onlinesys.domain.modules.finance.FinanceImg;
import com.origin.onlinesys.service.modules.finance.impl.FinanceCountServiceImpl;
import com.origin.onlinesys.service.modules.finance.impl.FinanceImgServiceImpl;
import com.origin.onlinesys.service.modules.finance.impl.FinanceServiceImpl;
import com.origin.onlinesys.web.utils.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by origin on 15-3-20.
 * 财务
 */
@Controller
@RequestMapping(value = "/management/finance")
public class FinanceController extends BaseController{
    @Autowired
    private FinanceServiceImpl financeService;
    @Autowired
    private FinanceCountServiceImpl financeCountService;
    @Autowired
    private FinanceImgServiceImpl financeImgService;
    private SimpleDateFormat sdf  = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private double balance;
    @RequestMapping(value = "/addIncome")
    public @ResponseBody
    Map addIncome(@ModelAttribute Finance finance){
        FinanceCount financeCount = financeCountService.selectFinanceCount(WebUtils.getAccount().getQueryZoneId());
        String id;
        FinanceCount countBean = new FinanceCount();
        if(financeCount != null){
            id = financeCount.getId();
            double leftMoneyCount = Double.parseDouble(financeCount.getLeftMoney())+Double.parseDouble(finance.getMoney());
            countBean.setLeftMoney(leftMoneyCount + "");
            countBean.setId(id);
            financeCountService.update(countBean);
            balance = leftMoneyCount - Double.parseDouble(financeCount.getPayMoney());
            finance.setBalance(balance+"");
        }else{
            countBean.setLeftMoney(finance.getMoney());
            countBean.setPayMoney("0");
            countBean.setZoneId(WebUtils.getAccount().getQueryZoneId());
            financeCountService.save(countBean);
            id = countBean.getId();
            finance.setBalance(finance.getMoney());
        }
        finance.setDate(sdf.format(new Date()));
        finance.setAddUId(WebUtils.getUserId());
        finance.setType("1");
        finance.setState("1");
        finance.setFinanceId(id);
        financeService.save(finance);
        Map map = financeService.selectBalance(WebUtils.getAccount().getQueryZoneId());
        map.put("leftMoney", dolFormat(map.get("leftMoney")));
        map.put("payMoney",dolFormat(map.get("payMoney")));
        map.put("yueCount",dolFormat(map.get("yueCount")));
        map.put("id",finance.getId());
        return map;
    }

    @RequestMapping(value = "/addPay")
    public @ResponseBody
    Map addPay(@ModelAttribute Finance finance){
        FinanceCount financeCount = financeCountService.selectFinanceCount(WebUtils.getAccount().getQueryZoneId());
        String id;
        FinanceCount countBean = new FinanceCount();
        if(financeCount != null){
            id = financeCount.getId();
            double leftMoneyCount = Double.parseDouble(financeCount.getPayMoney()) + Double.parseDouble(finance.getMoney());
            countBean.setPayMoney(leftMoneyCount+"");
            countBean.setId(id);
            financeCountService.update(countBean);
            balance = Double.parseDouble(financeCount.getLeftMoney()) - leftMoneyCount;
            finance.setBalance(balance+"");
        }else{
            countBean.setLeftMoney("0");
            countBean.setPayMoney(finance.getMoney());
            countBean.setZoneId(WebUtils.getAccount().getQueryZoneId());
            financeCountService.save(countBean);
            id = countBean.getId();
            finance.setBalance("-"+finance.getMoney());
        }
        finance.setDate(sdf.format(new Date()));
        finance.setAddUId(WebUtils.getUserId());
        finance.setHaveReceipt(WebUtils.getAccount().getFinanceImgList().size()>0?"1":"0");
        finance.setType("-1");
        finance.setState("1");
        finance.setFinanceId(id);
        financeService.save(finance);
        Map map = null;
        List<Map> financeImg = new ArrayList<Map>();
        for(String str:WebUtils.getAccount().getFinanceImgList()){
            map = new HashMap();map.put("financeId",finance.getId());map.put("imgId",str);
            financeImg.add(map);
        }if(WebUtils.getAccount().getFinanceImgList().size()>0)financeService.addBatchImg(financeImg);
        WebUtils.getAccount().getFinanceImgList().clear();

        Map map1 = financeService.selectBalance(WebUtils.getAccount().getQueryZoneId());
        map1.put("leftMoney",dolFormat(map1.get("leftMoney")));
        map1.put("payMoney",dolFormat(map1.get("payMoney")));
        map1.put("yueCount",dolFormat(map1.get("yueCount")));
        map1.put("id",finance.getId());
        return map1;
    }

    @RequestMapping(value = "/uploadBill",method = RequestMethod.POST)
    public @ResponseBody
    int uploadBill(HttpServletRequest request){
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        /**页面控件的文件流**/
        MultipartFile multipartFile = multipartRequest.getFile("file");
        /**获取文件的后缀**/
        String suffix = multipartFile.getOriginalFilename().substring
                (multipartFile.getOriginalFilename().lastIndexOf("."));
        /**拼成完整的文件保存路径加文件**/
        SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMddHHmmss");
        StringBuilder fileName = new StringBuilder();fileName.append(this.projectPath());fileName.append("/resources/finance1");
        File file1 = new File(fileName.toString());if(!file1.exists())file1.mkdirs();
        fileName.append("/"+dateformat.format(new Date()));fileName.append("_");fileName.append(UUID.randomUUID().toString());
        fileName.append(suffix);
        File file = new File(fileName.toString());
        try {
            multipartFile.transferTo(file);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        FinanceImg financeImg = new FinanceImg();
        financeImg.setDate(sdf.format(new Date()));
        financeImg.setImgUrl(fileName.substring(fileName.lastIndexOf("/")+1));
        financeImg.setState("1");
        financeImgService.save(financeImg);
        WebUtils.getAccount().getFinanceImgList().add(financeImg.getId());
        return 0;
    }

    @RequestMapping(value = "/findFinanceCount")
    public @ResponseBody
    Map findFinanceCount(){
        Map map = new HashMap();map.put("userName",WebUtils.getAccount().getRealname());
        map.put("financeCount",financeCountService.selectFinanceCount(WebUtils.getAccount().getQueryZoneId()));
        return map;
    }

    @RequestMapping(value = "/findIncome")
    public @ResponseBody
    Map findIncome(int pageNum,String incomeStartTime,String incomeEndTime){
        String date = sdf.format(new Date()).substring(0,8)+"01 00:00:00";
        incomeStartTime = incomeStartTime != null?incomeStartTime+" 00:00:00":date;
        incomeEndTime = incomeEndTime != null?incomeEndTime+" 23:59:00":null;
        return financeService.selectIncome(pageNum,10,WebUtils.getAccount().getQueryZoneId(),incomeStartTime, incomeEndTime);
    }

    @RequestMapping(value = "/findPay")
    public @ResponseBody
    Map findPay(int pageNum,String payStartTime,String payEndTime){
        String date = sdf.format(new Date()).substring(0,8)+"01 00:00:00";
        payStartTime = payStartTime != null?payStartTime+" 00:00:00":date;
        payEndTime = payEndTime != null?payEndTime+" 23:59:00":null;
        return financeService.selectPay(pageNum,10,WebUtils.getAccount().getQueryZoneId(),payStartTime,payEndTime);
    }

    @RequestMapping(value = "/findImg")
    public @ResponseBody
    List<FinanceImg> findImg(String id){
        return financeImgService.selectImgByFinanceId(id);
    }

    @RequestMapping(value = "/del")
    public @ResponseBody
    Map del(String id,String money,String left){
        left = left.equals("true")?"true":null;
        Finance finance = new Finance();finance.setId(id);
        financeService.delete(finance);
        financeCountService.updateFinanceCount(left,money,
                WebUtils.getAccount().getQueryZoneId());
        Map map = financeService.selectBalance(WebUtils.getAccount().getQueryZoneId());
        map.put("leftMoney",dolFormat(map.get("leftMoney")));
        map.put("payMoney",dolFormat(map.get("payMoney")));
        map.put("yueCount", dolFormat(map.get("yueCount")));
        return map;
    }
    private String dolFormat(Object number){
        String str = number.toString();
        if(str.indexOf(".") < 0){return str += ".00";
        }else{str += "00";}
       return str.substring(0,str.indexOf(".")+3);
    }
}
